/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.pointslottery.service;

import java.util.List;

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.modules.integralorders.entity.IntegralOrders;
import com.jeeplus.modules.integralorders.service.IntegralOrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.pointslottery.entity.PointsLottery;
import com.jeeplus.modules.pointslottery.mapper.PointsLotteryMapper;

/**
 * 积分商品Service
 * @author w
 * @version 2021-03-11
 */
@Service
@Transactional(readOnly = true)
public class PointsLotteryService extends CrudService<PointsLotteryMapper, PointsLottery> {

	@Autowired
	private IntegralOrdersService integralOrdersService;

	public PointsLottery get(String id) {
		return super.get(id);
	}
	
	public List<PointsLottery> findList(PointsLottery pointsLottery) {
		return super.findList(pointsLottery);
	}
	
	public Page<PointsLottery> findPage(Page<PointsLottery> page, PointsLottery pointsLottery) {
		return super.findPage(page, pointsLottery);
	}
	
	@Transactional(readOnly = false)
	public void save(PointsLottery pointsLottery) {
		if (pointsLottery.getIsNewRecord()){
			pointsLottery.setIsEnd("0");
			pointsLottery.setIsPrize("0");
			pointsLottery.setOriginalAmount(pointsLottery.getIntegralMember());
		}
		super.save(pointsLottery);
	}
	
	@Transactional(readOnly = false)
	public void delete(PointsLottery pointsLottery) {
		super.delete(pointsLottery);
	}

	/**
	 * 开奖
	 * @param pointsLottery
	 */
	@Transactional(readOnly = false)
	public AjaxJson makePrice(PointsLottery pointsLottery) {
		AjaxJson aj = new AjaxJson();
		IntegralOrders integralOrders = new IntegralOrders();
		integralOrders.setPointLottery(pointsLottery);
		List<IntegralOrders> list = integralOrdersService.findList(integralOrders);
		if (list.size()>0){
			if (list.stream().allMatch(integralOrders1 -> "1".equals(integralOrders1.getIsEnd()))){
				aj.setSuccess(false);
				aj.setMsg("该商品的订单已经开奖。");
				return aj;
			}
			//有设置中奖用户
			if (list.stream().anyMatch(integralOrders1 -> "1".equals(integralOrders1.getPrizeFlag()))){
				for (IntegralOrders orders : list) {
					orders.setIsEnd("1");
					integralOrdersService.save(orders);
				}
				pointsLottery.setIsPrize("1");
				save(pointsLottery);
			}else {
				aj.setSuccess(false);
				aj.setMsg("当前商品订单中未设置中奖用户，请设置完再开奖。");
				return aj;
			}
		}
		aj.setSuccess(true);
		aj.setMsg("开奖成功！");
		return aj;
	}
}